//
//  SkinManager.m
//  dyss_v2
//
//  Created by LXF on 16/3/2.
//  Copyright © 2016年 First Facility. All rights reserved.
//

#import "SkinManager.h"
#import "SkinTool.h"
#import "XXSkin.h"

@implementation SkinManager

+(instancetype)shared{
    static SkinManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

-(NSMutableSet *)nc_target{
    if (_nc_target == nil) {
        NSMutableSet<ReloadSkinResourceProtocal> *a = [[NSMutableSet<ReloadSkinResourceProtocal> alloc] init];
        _nc_target = a;
    }
    return _nc_target;
}

- (void)xx_register:(id)obj{
    [self.nc_target xx_addObject:obj];
}

- (void)xx_deRegister:(id)obj{
    [self.nc_target xx_removeObject:obj];
}


- (void)saveSkin:(XXSkin *)skin reloadSKinResource:(void (^)(NSString *str,CGFloat progress))progress completed:(void (^)())completed{
    [SkinTool saveSkin:skin.absPath];
    [self reloadSKinResource:progress completed:completed];
}

- (void)reloadSKinResource:(void (^)(NSString *str,CGFloat progress))progress completed:(void (^)())completed{
    
    __weak typeof(self) weakSelf = self;
    
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        progress(@"开始换肤..",0);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableSet *set = weakSelf.nc_target;
            NSUInteger count = set.count;
            if (count == 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    progress(@"换肤完毕..",1);
                    dispatch_group_leave(group);
                });
                return ;
            }
            __block NSUInteger currentIndex = 0;
            [set xx_enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
                currentIndex++;
                
                NSString *string = @"";
                
                if ([obj respondsToSelector:@selector(ReloadResourceShowMessage)]) {
                    string = [obj performSelector:@selector(ReloadResourceShowMessage)];
                }
                dispatch_group_enter(group);
                dispatch_async(dispatch_get_main_queue(), ^{
                    progress(string,(CGFloat)currentIndex / (CGFloat)count);
                    dispatch_group_leave(group);
                });
                dispatch_group_enter(group);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [obj performSelector:@selector(execReloadResource)];
                    dispatch_group_leave(group);
                });
                
            }];
            dispatch_group_leave(group);
        });
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        completed();
    });
}

@end
